package com.huajx.tuopuda.client.udp.codec.setting;

import com.huajx.tuopuda.client.udp.TuopudaUtil;
import com.huajx.tuopuda.client.udp.codec.AbstractCodec;
import com.huajx.util.CharUtil;
import com.huajx.util.HexUtil;
import com.huajx.util.StrUtil;

/**
 * 配置TCPIP[11F2]
 *
 * @author: lisa 叶新华
 * @create: 2019-09-28 19:32
 */
public class ConfigTcpIpCodec extends AbstractCodec {
    private int function = 0x11F2;

    private String mac = "00:57:47:01:A4:10";
    private String ip = "192.168.168.100";
    private String mask = "255.255.255.0";
    private String gateway = "192.168.168.254";
    private int port = 0xEA60;

    private ConfigTcpIpCodec(int sn) {
        setSn(sn);
    }

    public ConfigTcpIpCodec(int sn, String mac, String ip, String mask, String gateway, int port) {
        this(sn);
        this.mac = mac;
        this.ip = ip;
        this.mask = mask;
        this.gateway = gateway;
        this.port = port;
    }

    public static ConfigTcpIpCodec getInstance(int sn) {
        return new ConfigTcpIpCodec(sn);
    }

    @Override
    public byte[] encode() {
        String[] macArr = StrUtil.splitToArray(mac, CharUtil.COLON);
        String[] ipArr = StrUtil.splitToArray(ip, CharUtil.DOT);
        String[] maskArr = StrUtil.splitToArray(mask, CharUtil.DOT);
        String[] gatewayArr = StrUtil.splitToArray(gateway, CharUtil.DOT);

        return encode(getSn(), function, bytes -> {
            int checkSum = 0;
            for (int i = 0; i < macArr.length; i++) {
                checkSum += TuopudaUtil.replaceBytes(bytes, Integer.valueOf( macArr[i], 16), 5 + i, 1);
                if (i < ipArr.length) {
                    checkSum += TuopudaUtil.replaceBytes(bytes, Integer.valueOf(ipArr[i]), 11 + i, 1);
                    checkSum += TuopudaUtil.replaceBytes(bytes, Integer.valueOf(maskArr[i]), 15 + i, 1);
                    checkSum += TuopudaUtil.replaceBytes(bytes, Integer.valueOf(gatewayArr[i]), 19 + i, 1);
                }
            }

            checkSum += TuopudaUtil.replaceBytes(bytes, port, 23, 2);

            return checkSum;
        });
    }

    public String getMac() {
        return mac;
    }

    public void setMac(String mac) {
        this.mac = mac;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getMask() {
        return mask;
    }

    public void setMask(String mask) {
        this.mask = mask;
    }

    public String getGateway() {
        return gateway;
    }

    public void setGateway(String gateway) {
        this.gateway = gateway;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}
